from django.http import JsonResponse

from django.http import HttpResponse
from midproject import settings
from utils.login_dec import logging_check
from utils.payali import MyAlipay
from .models import Course, Order, Outline, Evaluate


# 支付宝支付账号   peyoxp2987@sandbox.com

def free_data_view(request):
    """
        获取免费课程页面的数据
    """
    course_query = Course.objects.all()
    dic = {}
    if not course_query:
        return JsonResponse(
            {
                "code": 10221,
                "data": dic
            }
        )
    for item in course_query:
        cname = item.course_name
        dic[item.id] = cname
        re2 = Order.objects.filter(course=item)
        num = str(len(re2)) + "人报名"
        dic[item.id + "y"] = num
    return JsonResponse(
        {
            "code": 200,
            "data": dic
        }
    )


def free_ddata_view(request, cid):
    """
        获取免费课程详情页面相关数据
    """
    img = ('v6', 'v7', 'v8', 'v9', 'v13')
    dic = {}
    re1 = Course.objects.filter(id=cid)
    if not re1:
        return JsonResponse(
            {
                "code": 10221,
                "data": dic
            }
        )
    dic["cname"] = re1[0].course_name
    dic["exp_time"] = "有效期：" + str(re1[0].course_life_time) + "天"

    re2 = Order.objects.filter(course=cid)
    num = len(re2)
    dic["enroll_num"] = "报名人数：" + str(num) + "人"
    if cid in img:
        sr = f"http://127.0.0.1:8000/static/images/{cid}.png"
        dic["src"] = sr
    else:
        sr = f"http://127.0.0.1:8000/static/images/{cid}.jpg"
        dic["src"] = sr
    return JsonResponse(
        {
            "code": 200,
            "data": dic
        }
    )


def pay_data_view(request):
    """
        获取付费课程页面的数据
    """
    course_query = Course.objects.all()
    dic = {}
    if not course_query:
        return JsonResponse(
            {
                "code": 10221,
                "data": dic
            }
        )
    for item in course_query:
        cname = item.course_name
        dic[item.id] = cname
        re2 = Order.objects.filter(course=item)
        num = str(len(re2)) + "人报名"
        dic[item.id + "y"] = num
        price = item.price
        dic[item.id + "p"] = price
    return JsonResponse(
        {
            "code": 200,
            "data": dic
        }
    )


def pay_ddataview(request, cid):
    """
        获取免费课程详情页面相关数据
    """
    img = ('p6', 'p7', 'p8', 'p9', 'p13')
    dic = {}
    re1 = Course.objects.filter(id=cid)
    if not re1:
        return JsonResponse(
            {
                "code": 10221,
                "data": dic
            }
        )
    dic["cname"] = re1[0].course_name
    dic["exp_time"] = "有效期：" + str(re1[0].course_life_time) + "天"

    re2 = Order.objects.filter(course=cid)
    num = len(re2)
    dic["enroll_num"] = "报名人数：" + str(num) + "人"

    dic["price"] = re1[0].price

    if cid in img:
        sr = f"http://127.0.0.1:8000/static/images/{cid}.png"
        dic["src"] = sr
    else:
        sr = f"http://127.0.0.1:8000/static/images/{cid}.jpg"
        dic["src"] = sr
    return JsonResponse(
        {
            "code": 200,
            "data": dic
        }
    )


def outline_view(request, v, vnum):
    """
        获取课程大纲
    """
    try:
        course_query = Course.objects.get(id="p1")
        re = Outline.objects.get(course=course_query)
    except:
        return JsonResponse(
            {
                "code": 10221,
                "error": "没有数据"
            }
        )
    dic = {}
    dic["outline1"] = re.name1
    dic["outline2"] = re.name2
    dic["outline3"] = re.name3
    dic["outline4"] = re.name4
    dic["outline5"] = re.name5

    return JsonResponse(
        {
            "code": 200,
            "data": dic
        }
    )


def introduce_view(request, v, vnum):
    """
        获取课程简介
    """
    try:
        introduce_query = Course.objects.get(id=vnum)
    except:
        return JsonResponse(
            {
                "code": 10221,
                "error": "没有数据"
            }
        )
    data = introduce_query.course_detail

    return JsonResponse(
        {
            "code": 200,
            "data": data
        }
    )


def comment_view(request, v, vnum):
    """
        获取课程评价
    """
    dic = {}
    try:
        course_query = Course.objects.get(id="p1")
        comment_query = Evaluate.objects.filter(course=course_query)
    except:
        return JsonResponse(
            {
                "code": 10221,
                "error": "没有数据"
            }
        )
    i = 1
    for c_query in comment_query:
        key = f"comment{i}"
        dic[key] = c_query.content
        i += 1

    return JsonResponse(
        {
            "code": 200,
            "data": dic
        }
    )


class PayCourse(MyAlipay):
    @logging_check
    def post(self, request, username):
        data = request.mydata
        user = request.myuser
        type = int(data.get("type"))
        if type not in (0, 1):
            return JsonResponse({
                'code': 10221,
                "error": "违法请求"
            })
        course_id = data.get("course_id")
        if type == 0:
            try:
                course = Course.objects.get(id=course_id)
            except:
                return JsonResponse({
                    'code': 10221,
                    "error": "违法请求"
                })

            # 查询该课程是否已经在订单中
            try:
                c_query = Order.objects.get(course=course, student=user)
                return JsonResponse({
                    'code': 10221,
                    "error": "已报名过该课程"
                })
            except Exception as e:
                price = course.price
                order = Order.objects.create(
                    course=course,
                    student=user,
                    market_price=price,
                )
                return JsonResponse({
                    'code': 200,
                    "data": "报名成功"
                })
        else:
            # 处理立即购买视图
            try:
                course = Course.objects.get(id=course_id)

            except:
                return JsonResponse({
                    'code': 10221,
                    "error": "违法请求"
                })

            # 查询该课程是否已经在订单中
            try:
                c_query = Order.objects.get(course=course, student=user)
                return JsonResponse({
                    'code': 10221,
                    "error": "已购买过该课程"
                })
            except:

                price = course.price
                order = Order.objects.create(
                    course=course,
                    student=user,
                    market_price=price,
                )
                order_id = order.id
                total_amount = order.market_price
                params = self.alipay.api_alipay_trade_page_pay(
                    # 订单标题
                    subject=order_id,
                    # 订单编号
                    out_trade_no=order_id,
                    # 订单总金额
                    total_amount=float(total_amount),
                    # 同步通知GET地址
                    return_url=settings.ALIPAY_RETURN_URL,
                    # 异步通知POST地址
                    notify_url=settings.ALIPAY_NOTIFY_URL
                )

                pay_url = "https://openapi.alipaydev.com/gateway.do?" + params
                return JsonResponse({
                    "code": 200,
                    "pay_url": pay_url
                })


class ReturnView(MyAlipay):
    def get(self, request):
        """
            同步通知
        """
        data = request.GET
        out_trade_no = data.get("out_trade_no")
        trade_no = data.get("trade_no")
        result = self.alipay.api_alipay_trade_query(
            out_trade_no=out_trade_no,
            trade_no=trade_no,
        )
        trade_status = result.get("trade_status")
        if trade_status == "TRADE_SUCCESS":
            return HttpResponse("购买成功")
        else:
            return HttpResponse("购买失败")


class NotifyView(MyAlipay):
    def post(self, request):
        """
           异步通知
        """
        data = request.POST
        sign = data.get("sign")
        rsult = self.alipay.verify(data=data, signature=sign)
        if rsult:
            trade_status = data.get("trade_status")
            if trade_status == "TRADE_SUCCESS":
                return HttpResponse("success")
            else:
                return HttpResponse("success")
        else:
            return HttpResponse("非法请求")
